package com.cscec5b.inspection.config;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public final class PasswordUtil {

    private PasswordUtil() {}

    public static String md5Hex(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(s.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder(32);
            for (byte b : digest) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5 calc failed", e);
        }
    }

    /** 明文 → MD5 → 再MD5，返回32位hex（小写） */
    public static String doubleMd5(String plain) {
        return md5Hex(md5Hex(plain));
    }

    /** 常量时间比较（减少时序侧信道，简化实现） */
    public static boolean constantTimeEquals(String a, String b) {
        if (a == null || b == null) return false;
        int len = Math.max(a.length(), b.length());
        int result = 0;
        for (int i = 0; i < len; i++) {
            char ca = i < a.length() ? a.charAt(i) : 0;
            char cb = i < b.length() ? b.charAt(i) : 0;
            result |= (ca ^ cb);
        }
        return result == 0;
    }
}
